<template>
	<view class="container">
		<button @click="downloadAndPreviewImage">下载并预览图片</button>
		<image v-if="imagePath" :src="imagePath" mode="widthFix" class="preview-image"></image>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				imageUrl: "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg",
				imagePath: ""
			};
		},
		methods: {
			downloadAndPreviewImage() {
				const imagetask = uni.downloadFile({
					url: this.imageUrl,
					success: (res) => {
						if (res.statusCode === 200) {
							console.log("下载成功，临时文件路径：", res.tempFilePath);
							this.imagePath = res.tempFilePath;
							uni.previewImage({
								urls: [res.tempFilePath]
							});
						}
					},
					fail: (err) => {
						console.error("下载失败：", err);
					}
				});
				imagetask.onProgressUpdate((res) => {
					console.log("下载进度：", res.progress + "%");
					console.log("已下载字节数：", res.totalBytesWritten);
					console.log("预期总字节数：", res.totalBytesExpectedToWrite);
				});
			}
		}
	};
</script>

<style scoped>
	.container {
		padding: 30rpx;
	}

	.preview-image {
		width: 100%;
		margin-top: 20rpx;
	}
</style>